/**
 * (created at 2011-1-23)
 */
package qiushuo.mysqlparser.ast.expression.primary.function.string;

import java.util.ArrayList;
import java.util.List;

import qiushuo.mysqlparser.ast.expression.Expression;
import qiushuo.mysqlparser.ast.expression.primary.function.FunctionExpression;
import qiushuo.mysqlparser.generator.SQLType;

/**
 * @author <a href="mailto:QiuShuo1985@gmail.com">QIU Shuo</a>
 */
public class Trim extends FunctionExpression {
    private final String direction;

    private static List<Expression> wrapList(Expression str, Expression remstr) {
        List<Expression> list = new ArrayList<Expression>(2);
        list.add(str);
        if (remstr != null) list.add(remstr);
        return list;
    }

    public Trim(String direction, Expression remstr, Expression str) {
        super("TRIM", wrapList(str, remstr));
        this.direction = direction;
    }

    @Override
    public FunctionExpression constructFunction(List<Expression> arguments) {
        throw new UnsupportedOperationException("function of char has special arguments");
    }

    @Override
    public String generateSql(SQLType type) {
        switch (type) {
        case MySQL:
            boolean from = false;
            StringBuilder sb = new StringBuilder();
            sb.append("TRIM(");
            if (direction != null) {
                from = true;
                sb.append(direction).append(' ');
            }
            if (arguments.size() > 1) {
                from = true;
                sb.append(arguments.get(1).generateSql(type));
            }
            if (from) {
                sb.append(" FROM ");
            }
            sb.append(arguments.get(0).generateSql(type));
            sb.append(")");
            return sb.toString();
        default:
            throw new UnsupportedOperationException("only mysql sql can be generated");
        }
    }

}
